package com.android.common.base;

import com.android.common.constant.Constant;
import com.android.common.mvp.model.CodeMsgBean;
import com.android.common.utils.RxUtils;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import java.util.Objects;

public abstract class BaseObserver<T> implements Observer<T> {

    /**
     * 订阅消息的接口名
     */
    protected String mMethodName;

    protected BaseView mBaseView;
    private Disposable mDisposable;

    protected BaseObserver(BaseView baseView,String methodName){
        mBaseView = baseView;
        mMethodName = methodName;
    }
    @Override
    public void onSubscribe(Disposable d) {
        mDisposable = d;
    }

    @Override
    public void onNext(T t) {
        onSuccess(t);
    }

    @Override
    public void onError(Throwable e) {
        failed(Constant.ERROR,e.getMessage());
    }

    protected void failed(int code, String msg){
        CodeMsgBean result = new CodeMsgBean();
        result.setCode(code);
        result.setMessage(msg);
        Objects.requireNonNull(mBaseView).onFailed(result,mMethodName);
        unSubscribe();
    }


    @Override
    public void onComplete() {
        unSubscribe();
    }

    private void unSubscribe(){
        RxUtils.dispose(mDisposable);
    }

    protected abstract void onSuccess(T t);
}
